import { createRouter, createWebHistory } from 'vue-router'
import Login from '../views/Login.vue'
import Register from '../views/Register.vue'
import DashboardLayout from '../components/DashboardLayout.vue'
import PermissionLayout from '@/views/permissions/PermissionLayout.vue'
import DashboardPermission from '@/views/permissions/DashboardPermission.vue'
import { getDashboardList } from '@/api/dashboard'
import { getDashboardData } from '@/api/analysis'
import { ElMessage } from 'element-plus'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      component: () => import('@/components/DashboardLayout.vue'),
      children: [
        {
          path: 'analysis',
          component: () => import('@/views/analysis/AnalysisLayout.vue'),
          children: [
            {
              path: 'core',
              component: () => import('@/views/analysis/CoreAnalysis.vue')
            },
            {
              path: 'product',
              component: () => import('../views/analysis/ProductAnalysis.vue')
            },
            {
              path: 'customer',
              component: () => import('../views/analysis/CustomerAnalysis.vue')
            },
            {
              path: 'shop',
              component: () => import('../views/analysis/ShopAnalysis.vue')
            },
            {
              path: 'income',
              component: () => import('../views/analysis/IncomeAnalysis.vue')
            },
            {
              path: 'detail',
              component: () => import('../views/analysis/DetailAnalysis.vue')
            },
            {
              path: ':id',
              name: 'DashboardViewer',
              component: () => import('@/components/DashboardViewer.vue'),
              meta: {
                requiresAuth: true,
                title: '仪表板查看'
              }
            }
          ]
        },
        {
          path: 'permissions',
          component: PermissionLayout,
          children: [
            {
              path: 'dashboard/:id',
              component: DashboardPermission,
              name: 'DashboardPermission'
            }
          ]
        },
        {
          path: 'create',
          name: 'CreateDashboard',
          component: () => import('@/views/dashboard-manage/CreateDashboard.vue'),
          meta: {
            requiresAuth: true,
            requiresAdmin: true
          }
        },
        {
          path: 'sales',
          // component: () => import('@/views/sales/SalesDashboard.vue')
        },
        {
          path: '',
          redirect: '/analysis/core'
        }
      ]
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/Login.vue')
    },
    {
      path: '/register',
      name: 'register',
      component: () => import('@/views/Register.vue')
    },
  ]
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  // 登录检查
  if (to.name !== 'login' && to.name !== 'register' && !localStorage.getItem('token')) {
    next({ name: 'login' })
    return
  }

  const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')

  // 权限检查
  if (to.path.startsWith('/permissions') && userInfo.role !== 'ADMIN') {
    ElMessage.error('无权访问该页面')
    next('/analysis')
    return
  }

  // 检查仪表板访问权限
  if (to.path.startsWith('/analysis/') && userInfo.role !== 'ADMIN') {
    const type = to.path.split('/')[2] // 获取仪表板类型
    try {
      const data = await getDashboardData(type)
      if (!data.hasPermission) {
        ElMessage.error('无权访问该页面')
        next('/analysis')
        return
      }
    } catch (error) {
      console.error('检查权限失败:', error)
      next('/analysis')
      return
    }
  }

  next()
})

export default router 